# -*- coding:utf-8 -*-
from coffin.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.http import Http404
from django.template.context import RequestContext
from jpkc.forms import QuestionForm
from jpkc.models import Column, Article

def index(request):
    return column(request)


def column(request, cid = Column.first_id()):
    try:
        cid = int(cid)
    except:
        raise Http404
    current_col = get_object_or_404(Column, pk=cid)

    ret = {}
    #如果是一级栏目且有子栏目，则默认显示第1个子栏目
    if current_col.is_root_node() and len(current_col.get_children()):
        current_col = current_col.get_children()[0]

    if current_col.article_set.count():
        template_name = 'column_with_articles.html'
    else:
        template_name = 'column.html'
    ret['root_columns'] = Column.objects.root_nodes()

    ret['s_columns'] = current_col.get_siblings(True)
    ret['current_col'] = current_col
    ret['trav_list'] = current_col.trver_list()

    return render_to_response(template_name, ret, context_instance=RequestContext(request))


def article(request, aid = Article.first_id()):
    try:
        aid = int(aid)
    except:
        raise Http404
    article = get_object_or_404(Article, pk=aid)
    ret = {'article': article, 'root_columns': Column.objects.root_nodes()}
    current_col = article.column
    ret['s_columns'] = current_col.get_siblings(True)
    ret['current_col'] = current_col
    ret['trav_list'] = current_col.trver_list()
    return render_to_response('article.html', ret, context_instance=RequestContext(request))


def ask(request):
    form = QuestionForm(auto_id=True)
    return render_to_response('ask.html', {'form': form}, context_instance=RequestContext(request))